package concurrencyPractice.chapter04;

import concurrencyPractice.NotThreadSafe;
import concurrencyPractice.ThreadSafe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序4-14 4-15
 * @date 2023/12/29 15:10:47
 */

public class ListHelper<E> {
    public List<E> list = Collections.synchronizedList(new ArrayList<E>());

//    程序4-14 非线程安全的”若没有就添加方法“
    @NotThreadSafe
    public synchronized boolean putIfAbsent(E x) {
        boolean absent = !list.contains(x);

        if(absent) {
            list.add(x);
        }
        return absent;
    }

    @ThreadSafe
    public boolean SafePutIfAbsent(E x) {
        synchronized (list) {
            boolean absent = !list.contains(x);

            if(absent) {
                list.add(x);
            }
            return absent;
        }
    }


}
